<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/14
 * Time: 21:28
 */

namespace App\Http\Controllers\DfPay;


use App\Constant;
use App\Http\Controllers\Controller;
use App\Models\ManualDfMethod;
use App\Models\Payment;
use App\Services\DfChannel\CallBackParameter;
use App\Services\DfChannel\DfChannelFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class NotifyController extends Controller
{

    /**
     * 通道回调通知接口网关处理
     *
     * @param Request $request
     * @return mixed|void
     */
    public function index(Request $request)
    {
        Log::info("上游回调请求参数：" .json_encode($request->all()));

        // 载入可能存在的通知单号参数名
        $availableNameList = CallBackParameter::load();
        foreach ($availableNameList as $key=>$name) {
            if(!empty($request->input($name))) {
                $trade_no = $request->input($name);
                continue;
            }
        }
        if(empty($trade_no)) {
            return;
        }
        $payment_model = Payment::where("trade_no", $trade_no)->first();
        $withdraw_model = $payment_model->withdraw;
        $channel_model = ManualDfMethod::find($payment_model->channel_id);

        $client = DfChannelFactory::getChannel($channel_model->code);
        if(empty($client)) {
            return $client->response(false);
        }

        // 通道验签逻辑
        if(!$client->verify($channel_model->appsecret, $request->all())) {
            Log::info('验签失败！');
            return $client->response(false);
        }

        if(!$client->checkStatus($request->all())) {
            return $client->response(false);
        }

        DB::beginTransaction();
        $payment_model->fill(['response' => json_encode($request->all())])->save();
        $withdraw_model->fill(['status' => Constant::YES])->save();
        DB::commit();

        return $client->response();
    }


    /**
     * 创建签名
     * @param $Md5key
     * @param $list
     * @return string
     */
    protected function createSign($Md5key, $list)
    {
        ksort($list);
        $md5str = "";
        foreach ($list as $key => $val) {
            if (!empty($val)) {
                $md5str = $md5str . $key . "=" . $val . "&";
            }
        }
        $md5str = trim($md5str, '&');
        $sign = (md5( $Md5key. $md5str .  $Md5key));
        return $sign;
    }
}